﻿#include "session_recycler.h"
#include "common.h"
#include "forward_session.h"
#include <stdio.h>

session_recycler* session_recycler::instance = NULL;

session_recycler::session_recycler() : head_ptr(NULL), tail_ptr(NULL)
{
}

session_recycler::~session_recycler(){

}

session_recycler* session_recycler::get_instance(){
	if (instance == NULL){
		instance = new session_recycler();
	}
	return instance;
}
	
void session_recycler::destroy_instance(){
	if (instance != NULL){
		delete instance;
		instance = NULL;
	}
}

void session_recycler::push_back(timer_domain& td){
	if (td.session_ptr != NULL){ 
		LOGI("push_back %s", td.session_ptr->to_string());
	}else{
		LOGI("push_back NULL");
	}
	if (is_empty()){
		td.prev = NULL;
		td.next = NULL;
		head_ptr = &td;
		tail_ptr = &td;
	}else{
		td.prev = tail_ptr;
		td.next = NULL;
		tail_ptr->next = &td;
		tail_ptr = &td;
	}
	td.retick();
}

timer_domain* session_recycler::remove_front(){
	timer_domain* domain = NULL;
	if (is_empty()){
	}
	else if (head_ptr == tail_ptr){
		domain = head_ptr;
		head_ptr->prev = NULL;
		head_ptr->next = NULL;
		head_ptr = NULL;
		tail_ptr = NULL;				
	}else{
		timer_domain* new_head = head_ptr->next;
		domain = head_ptr;
		head_ptr->prev = NULL;
		head_ptr->next = NULL;	
		head_ptr = new_head;
		head_ptr->prev = NULL;	
	}
	return domain;
}

void session_recycler::remove(timer_domain& td){
	
	if (td.session_ptr != NULL){
		LOGI("remove %s", td.session_ptr->to_string());
	}else{
		LOGI("remove NULL");
	}
	if (head_ptr == &td){
		head_ptr = td.next;
	}

	if (tail_ptr == &td){
		tail_ptr = td.prev;
	}
	
	if (td.prev != NULL){
		td.prev->next = td.next;
	}
	if (td.next != NULL){
		td.next->prev = td.prev;
	}
	td.prev = NULL;
	td.next = NULL;
}

void session_recycler::reorder(timer_domain& td){
	if (td.session_ptr != NULL){
		LOGI("reorder %s", td.session_ptr->to_string());
	}else{
		LOGI("reorder NULL");
	}
	remove(td);
	push_back(td);

	print_list();
}

void session_recycler::print_list(){
	timer_domain* cur = head_ptr;
	LOGI("----------------> session_recycler print_list ---------------->\n");
	int i = 0;
	for(cur = head_ptr;cur!=NULL; cur= cur->next){
		LOGI("%d) session=%u", i, (unsigned int)cur->session_ptr);
	}
	LOGI("<---------------- session_recycler print_list <----------------\n");
}

